<template>

</template>

<script>
    import {getToken, getUserInfo} from '@api/auth'

    var isPageHide = false;
    window.addEventListener('pageshow', function () {
        if (isPageHide) {
            window.location.reload()
        }
    })
    window.addEventListener('pagehide', function () {
        isPageHide = true
    })
    export default {
        name: "ihub_callback",
        components: {},
        data() {
            return {}
        },
       mounted() {
            let code = this.$route.query.code
            let redirect = this.$route.query.redirect
            if (!redirect) {
                alert('redirect_url 为空')
            }
            if(code==sessionStorage.getItem('backCode'))
            {
              window.history.go(-2);
            }
            sessionStorage.setItem('backCode',code);
            redirect = decodeURIComponent(escape(window.atob(redirect)));
            if (code) {
                getToken({code: code}).then(res => {
                    if (res.successful) {
                        let token = res.data.token
                        if (token) {
                            sessionStorage.setItem('access-token', token)
                            getUserInfo().then(res => {
                                if (res.successful) {
                                    sessionStorage.setItem('bu', res.data.bu)
                                    sessionStorage.setItem('name', res.data.name)
                                    sessionStorage.setItem('email', res.data.email)
                                    sessionStorage.setItem('avatar', res.data.thumb_avatar)
                                    sessionStorage.setItem('wx_userid', res.data.wxUserId)
                                    let wx_userid = res.data.wxUserId
                                    let href_uri = ''
                                    if (redirect.indexOf('?') != -1) {
                                        href_uri = redirect + '&userid=' + wx_userid
                                    } else {
                                        href_uri = redirect + '?userid=' + wx_userid
                                    }
                                  window.location.href = href_uri
                                } else {
                                    alert('获取用户数据异常，请联系后台管理员。')
                                }
                            })
                        } else {
                            alert("获取用户token为空，请联系后台管理员验证用户信息。")
                        }
                    } else {
                        alert("获取token接口异常，请联系后台管理员。")
                    }
                })
            } else {
                alert('未获取到授权码，请联系后台管理员添加授权账号。')
            }
        }
    }
</script>

<style scoped>

</style>